package com.lx.common.utils;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;

import javax.persistence.Column;
import javax.persistence.JoinColumn;
import java.lang.reflect.Field;

/**
 * 针对SQL处理时需要用到的类型解析工具
 *
 * @author lx
 * @create 2023/2/25 19:38
 **/
public class SqlClassUtil {

    private SqlClassUtil() {
    }

    /**
     * 2.获取 {@link Column}的name.
     * 3.获取 {@link JoinColumn}的name.
     * 4.获取 属性名称,根据列定义判断是否使用驼峰命名法定义.
     *
     * @param isHQL       是否获取HQL语法的属性
     * @param columnField
     * @param openHump    是否启用驼峰命名法解析属性名
     * @return
     */
    public static final String findColumnNameByField(boolean isHQL, Field columnField, boolean openHump) {
        if (columnField == null) {
            return null;
        }
        //一定不会为空!
        String columnName = columnField.getName();

        if (isHQL) {
            //如果是Hql,则只需要返回属性名即可.
            return columnName;
        }
        //整合SQL列名
        JoinColumn joinColumn = columnField.getAnnotation(JoinColumn.class);
        if (joinColumn != null && StrUtil.isNotEmpty(columnName = joinColumn.name())) {
            return columnName;
        }

        Column col = columnField.getAnnotation(Column.class);
        if (col != null && StrUtil.isNotEmpty((columnName = col.name()))) {
            return columnName;
        }

        return openHump ? CharSequenceUtil.toUnderlineCase(columnName) : columnName;
    }

}
